package io.flash.rpc.protocol;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.Semaphore;

@Data
@NoArgsConstructor
public class RpcRequestPacket {

    private String requestId;
    private String serviceClassName;
    private String methodName;
    private String param;

    @JSONField(serialize = false)
    private Semaphore semaphore;

    public <T> RpcRequestPacket(Class<T> serviceClass, Method method, Object[] args) {
        requestId = UUID.randomUUID().toString();
        semaphore = new Semaphore(0);

        serviceClassName = serviceClass.getName();
        methodName = method.getName();
        param = JSON.toJSONString(args[0]);
    }

    public void waitResponse() {
        semaphore.acquireUninterruptibly();
    }

    public void receiveResponse() {
        semaphore.release();
    }
}
